package servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import burhan.bean.NotificationBean;


@SuppressWarnings("serial")
public class TransactionServlet extends HttpServlet {
	
	private boolean isPost = false;
	private UserService userService;
	private User user;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		userService = UserServiceFactory.getUserService();
        user = userService.getCurrentUser();
		
		String pathinfo = request.getPathInfo();
		if(pathinfo == null || "/".equals(pathinfo)){
			listTransactions(request, response);
		} else if(pathinfo.startsWith("/add")){
			addTransaction(request, response);
		} else if(pathinfo.startsWith("/edit")){
			editTransaction(request, response);
		}
	}
	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		isPost = true;
		doGet(request, response);
	}
	
	
	private void listTransactions(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    Key transactionKey = KeyFactory.createKey("UserTransactions", user.getUserId());
	    Query query = new Query("Transaction", transactionKey).addSort("date", Query.SortDirection.DESCENDING);
	    List<Entity> transactions = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
	    for (Entity t : transactions) {
           response.getWriter().println("type:"+t.getProperty("type"));
           response.getWriter().println("<br/>");
           response.getWriter().println("date:"+t.getProperty("date"));
           response.getWriter().println("<br/>");
           response.getWriter().println("amount:"+t.getProperty("amount"));
        }
		
		/*RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/list.jsp");
		try {
			rd.forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}
	
	private void addTransaction(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		NotificationBean notificationBean =  new NotificationBean();
		if(isPost){
			// recive post data
			String type = request.getParameter("type");
			String dateStr = request.getParameter("date");
			String amountStr = request.getParameter("amount");
			String description = request.getParameter("description");
			
			// valiadation
			Date date = null;
			float amount = 0;			
			type = "EARNING".equals(type) ? "EARNING" : "EXPENSE";
			try {
				DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
				date = formatter.parse(dateStr);
			} catch (ParseException e) {
				// do nothing
			}
			try
			{
				amount = Float.valueOf(amountStr).floatValue();
			} catch (Exception e) {
				// do nothing
			}
			
			// set notifications
			if(date == null){
				notificationBean.addError("Please enter a valid date");
			}
			if(amount == 0){
				notificationBean.addError("Please enter an valid amount");
			}
			
			// store data
			if(notificationBean.getErrorCount() == 0 ){
				
		        Key transactionKey = KeyFactory.createKey("UserTransactions", user.getUserId());

		        Entity t = new Entity("Transaction", transactionKey);
		        t.setProperty("type", type);
		        t.setProperty("date", date);
		        t.setProperty("amount", amount);
		        t.setProperty("description", description);

		        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		        datastore.put(t);
			}
		}
		request.setAttribute("notificationBean", notificationBean);
		RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/form.jsp");
		try {
			rd.forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void editTransaction(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		response.getWriter().println("Transaction edit");
	}
}
